<template>
  <div class="app-container">
    <div class="head-container">
      <el-input class="filter-item" size="small" style="width: 160px;"
                :v-show="txtQuery.length>1"
                v-for="(item, index) in txtQuery"
                :key="index"
                v-model="listQuery[item.vModel]"
                :placeholder="item.placeholder"
                clearable>
      </el-input>

      <el-select
        :v-show="selectQuery.length>1"
        v-for="(item, index) in selectQuery"
        :key="index"
        v-model="listQuery[item.vModel]"
        class="filter-item"
        :placeholder="item.placeholder"
        clearable
        filterable
      >
        <el-option
          v-for="dict in selectList[item.vModel] "
          :key="dict.id"
          :label="dict.name"
          :value="dict.code"
        >
        </el-option>

      </el-select>
      <el-date-picker
        :v-show="dateQuery.length>1"
        v-for="(item, index) in dateQuery"
        :key="index"
        v-model="listQuery[item.vModel]"
        type="date"
        class="filter-item"
        :placeholder="item.placeholder"
        clearable
      >
      </el-date-picker>
      <el-button
        class="filter-item"
        type="success"
        icon="el-icon-search"
        size="mini"
        @click="getTablePage(true)"
      >
        查询
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="openDialogTableForm(0)"
      >新增
      </el-button>
    </div>
    <div class="head-container">
      <el-table
        ref="genTable"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column type="index" width="50" label="序号">
          <template slot-scope="scope">
            <span>{{(listQuery.pageNo -1)* listQuery.pageSize +scope.row.listIndex + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          v-for="(item, index) in columnsList"
          :key="index"
          :min-width="item.vueLength"
          :prop="item.fieldCode"
          :label="item.vueLabel">
        </el-table-column>
        <el-table-column align="left" label="操作" min-width="260">
          <template slot-scope="scope">
            <div v-if="procDefName">
              <dynamic-btn
                :type="scope.row.btnList"
                :row="scope.row"
                @edit="edit"
                @del="handleDelete"
                @detail="detail"
                @approve="approve"
                @apply="apply"
              />
            </div>
            <div v-else>
              <el-button style="margin-left: 10px" type="success" size="mini" @click="openDialogTableForm(1,scope.row)">
                修改
              </el-button>
              <el-button style="margin-left: 10px" type="danger" size="mini" @click="handleDelete(scope.row)">删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页组件-->
    <el-pagination
      style="margin-top: 8px;"
      layout="total, prev, pager, next"
      :page-size="listQuery.pageSize"
      :total="total"
      prev-text="上一页"
      next-text="下一页"
      :current-page="listQuery.pageNo"
      @current-change="paginationChange"
    >
    </el-pagination>
    <!-- 弹出框新增table -->
    <cus-dialog
      v-dialog-drag
      ref="widgetPreview"
      :visible="previewVisible"
      :showBtn="false"
      width="100$"
      form
      @on-close="previewVisible = false"
    >
      <el-tabs v-model="activeName" tab-position="right">
        <el-tab-pane name="first" ref="first" label="详细信息">
          <generate-form v-if="previewVisible" ref="generateForm" insite="true" :data="formJson" :value="widgetModels"
                         :remote="remoteFuncs" @on-change="handleDataChange">
            <template v-slot:blank="scope">
              Width
              <el-input v-model="scope.model.blank.width" style="width: 100px"/>
              Height
              <el-input v-model="scope.model.blank.height" style="width: 100px"/>
            </template>
          </generate-form>

          <work-flow-pop
            v-if="procDefName"
            ref="btn"
            :row="widgetModels"
            :procDefkey="procDefName"
            @save="saveTable"
            @apply="onApply"
            @approve="onApprove"
            @cancel="cancel"
            @reject="onReject"
          />
        </el-tab-pane>
        <el-tab-pane name="second" ref="first" @tab-click="tabClick" label="审批记录" v-if="instanceId">
          <wf-process :inst-id="instanceId"/>
        </el-tab-pane>
      </el-tabs>

      <template v-if="!procDefName" slot="action">
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="editType != 2" type="primary" @click="saveTable">保 存</el-button>
      </template>
    </cus-dialog>
  </div>
</template>

<script>
  import {edit, loadModuleData, doCrud, getDictList, fieldProps, doWfCrud} from '@/api/system/dynamic'
  import {startItem, completeItem} from '@/api/wf/workflow'
  import startMixin from '@/mixins/wfStartMixin'
  import approveMixin from '@/mixins/wfApproveMixin'
  import msgUtil from '@/utils/msgUtil'
  import DynamicBtn from '@/components/WorkFlow/dynamicBtn'
  import CusDialog from '../../components/VueForm/CusDialog'
  import GenerateForm from '../../components/VueForm/GenerateForm'
  import WfProcess from '@/components/WorkFlow/process/index'
  import WorkFlowPop from '@/components/WorkFlow/dynamicBtn/pop/index'

  let Base64 = require('js-base64').Base64;
  export default {
    components: { WfProcess, DynamicBtn, CusDialog, GenerateForm, WorkFlowPop},
    mixins: [startMixin, approveMixin],
    data() {
      return {
        previewVisible: false,
        formJson: '',
        originalFormJson: '',
        widgetModels: {},
        remoteFuncs: {},
        menus: [],
        editType: 0,
        moduleFormId: '',
        activeName: 'first',
        selTableId: 0, // 选中行的tableId
        detailId: '',//详情id
        selType: 0, // 选中的创建文件类型
        tableKey: 0,
        list: null,
        listLoading: false,
        total: 0,
        columnsList: [],
        formList: [],
        selectQuery: [],
        dictArr: [],
        dateQuery: [],
        txtQuery: [],
        queryParams: '',
        procDefName: null,
        instanceId: null,
        listQuery: {
          pageNo: 1,
          pageSize: 10,
          condition: '',
          seat: 5,
        },
        selectList: {
          tableList: [],
        },
        rules: {}
      }
    },
    created() {
      let path = this.$route.path
      const index = path.lastIndexOf('/')
      path = path.substr(index + 1)
      if (path.length == 0) {
        path = this.$route.path
      }
      this.loadModuleDataFuc(path).then(() => {
        this.getTablePage()
      })
    },
    methods: {
      handleDataChange() {
      },
      tabClick() {
        const w = this.$refs.first[0].style.height
        this.$refs.second[0].style.maxHeight = `${w}px`
      },
      loadModuleDataFuc(moduleFormId) {
        this.moduleFormId = moduleFormId
        return loadModuleData(moduleFormId).then(res => {
          this.formJson = JSON.parse(res.data.formJson)
          this.originalFormJson = JSON.parse(res.data.formJson)
          this.columnsList = res.data.listFormList
          this.formList = res.data.formList

          this.procDefName = res.data.procDefName
          this.queryParams = res.data.queryParams
          let params = {'pageNo': this.listQuery.pageNo, 'pageSize': this.listQuery.pageSize}
          //加载查询代码
          this.loadQueryCode(this.columnsList, this.queryParams)
          if (this.queryParams !== '') {
            this.queryParams.split(',').forEach(item => {
              params[item] = this.listQuery[item] === undefined ? '' : this.listQuery[item]
            })
          }
          let paramsJson = JSON.stringify(params)
          let selectPageParams = {
            type: 'selectPage',
            moduleFormId: this.moduleFormId,
            paramsJson: Base64.encodeURI(paramsJson),
          }
          this.loadCrud('selectPage', selectPageParams)
        })
      },

      loadQueryCode(columns, queryParams) {
        columns.forEach(item => {
          if (item.isQuery === 1) {
            let jsonStr = {
              'vModel': item.fieldCode,
              'placeholder': item.fieldDesc
            }
            this.$set(this.listQuery, item.fieldCode, '')
            if (item.vueType.indexOf('日期') !== -1) {
              this.dateQuery.push(jsonStr)
            } else if (item.vueType.indexOf('下拉框') !== -1) {
              this.selectQuery.push(jsonStr)
              if (item.vueType.indexOf('下拉框字典') !== -1) {
                this.dictArr.push(item.fieldCode)
                this.loadDict(item.fieldCode);
              }
            } else {
              this.txtQuery.push(jsonStr)
            }
          }
        })
        //特殊：添加创建起始和截止日期
        if (queryParams.indexOf('createTimeFrom') !== -1) {
          this.dateQuery.push({'vModel': 'createTimeFrom', 'placeholder': '创建起始日期'})
        }
        if (queryParams.indexOf('createTimeTo') !== -1) {
          this.dateQuery.push({'vModel': 'createTimeTo', 'placeholder': '创建截止日期'})
        }
      },
      //加载字典
      loadDict(dictCode) {
        getDictList(dictCode).then(res => {
          this.$set(this.selectList, dictCode, res.data)
          let func_DictCode = 'func_' + dictCode
          this.$set(this.remoteFuncs, func_DictCode, this.selectList[dictCode])
        }).catch((res) => {
        })
      },
      loadCrud(type, params) {
        let fn;
        if (type === 'selectPage' && this.procDefName) {
          fn = doWfCrud
        } else {
          fn = doCrud
        }
        fn(params).then(res => {
          if (type === 'selectPage') {
            this.list = res.data.list
            res.data.list.forEach((item, index) => {
              item.listIndex = index
              for (let key in item) {
                if (this.dictArr.includes(key)) {
                  let dict = this.selectList[key].find((dict) => item[key] == dict.code);
                  item[key] = dict.name
                }
              }
            });
            this.total = res.data.total
          } else if (type === 'insert') {
            this.previewVisible = false
            msgUtil.success2('数据表新增成功!')
            this.getTablePage()
          } else if (type === 'update') {
            this.previewVisible = false
            msgUtil.success2('数据表更新成功!')
            this.getTablePage()
          }
        }).catch((res) => {
        })
      },
      onApprove(form, approve) {
        this.approveForm = Object.assign(this.approveForm, approve)
        this.approveForm.procDefKey = this.procDefName
        this.approveForm.selectAssigneeList = approve.nextUser
        this.approveForm.entity = Object.assign({}, this.widgetModels)
        // 流程实例编号
        this.approveForm.procInstId = this.instanceId
        this.approveForm.entity.btn = null
        completeItem(this.approveForm).then(r => {
          msgUtil.success2('审批成功!')
          this.previewVisible = false
          this.getTablePage(true)
        })
      },
      onApply(form) {
        this.startForm.id = this.detailId
        this.startForm.multi = form.multi
        this.startForm.procDefKey = this.procDefName
        this.startForm.selectAssigneeList = form.nextUser
        this.startForm.entity = Object.assign({}, this.widgetModels)
        this.startForm.entity.btn = null
        startItem(this.startForm).then(r => {
          msgUtil.success2('上报成功!')
          this.previewVisible = false
          this.getTablePage(true)
        })
      },
      onReject(form, approve) {
        this.approveForm = Object.assign(this.approveForm, approve)
        this.approveForm.entity = Object.assign({}, this.widgetModels)
        this.approveForm.procInstId = this.instanceId
        completeItem(this.approveForm).then(r => {
          msgUtil.success2('审批成功!')
          this.previewVisible = false
          this.getTablePage(true)
        })
      },
      cancel() {
        this.previewVisible = false
        for (const i in this.widgetModels) {
          this.widgetModels[i] = ''
        }
      },
      // 保存数据表配置
      saveTable() {
        if (this.editType == 1) {
          this.$refs.generateForm.getData().then(paramJson => {
            paramJson.id = this.detailId
            let updateParams = {
              type: 'update',
              moduleFormId: this.moduleFormId,
              paramsJson: Base64.encodeURI(JSON.stringify(paramJson)),
            }
            this.loadCrud('update', updateParams)
          })
        } else {
          this.$refs.generateForm.getData().then(paramJson => {
            let insertParams = {
              type: 'insert',
              moduleFormId: this.moduleFormId,
              paramsJson: Base64.encodeURI(JSON.stringify(paramJson)),
            }
            this.loadCrud('insert', insertParams)
          })
        }
      },
      // 删除
      handleDelete(row) {
        msgUtil.confirm('确认删除表数据?').then(async () => {
          let params = {id: row.id}
          let deleteParams = {
            type: 'delete',
            moduleFormId: this.moduleFormId,
            paramsJson: Base64.encodeURI(JSON.stringify(params))
          }
          await doCrud(deleteParams).then(res => {
          }).catch((res) => {
          })
          msgUtil.success2('删除成功!')
          this.getTablePage()
        })
      },
      paginationChange(index) {
        this.listQuery.pageNo = index
        this.getTablePage()
      },
      getTablePage(reload) {
        if (reload) {
          this.listQuery.pageNo = 1
        }
        this.listLoading = true
        let paramsJson = JSON.stringify(this.listQuery)
        let selectPageParams = {
          type: 'selectPage',
          moduleFormId: this.moduleFormId,
          paramsJson: Base64.encodeURI(paramsJson),
        }
        this.loadCrud('selectPage', selectPageParams)
        this.$nextTick(() => {
          this.listLoading = false
        })
      },
      handleSelectionChange(val) {
        if (val.length > 1) {
          this.$refs.genTable.clearSelection()
          this.$refs.genTable.toggleRowSelection(val[val.length - 1])
        } else if (val.length === 0) {
          this.selTableId = 0
        } else {
          this.selTableId = val[0].id
        }
      },
      edit(row) {
        this.openDialogTableForm(1, row)
      },
      approve(row) {
        //todo
        // this.formJson.list

        fieldProps(row.instanceId).then(res => {
          let showProp = []//当前环节显示的属性
          res.data.forEach(item => {
            showProp.push(item.id)
          })
          let formJson = JSON.parse(JSON.stringify(this.originalFormJson))
          formJson.list.forEach(grid => {
            grid.columns.forEach(column => {
              if (showProp.includes(column.list[0].model)) {
                return
              } else {
                column.list = []
              }
            })
          })
          this.formJson = formJson
          this.openDialogTableForm(2, row)
        })
      },
      detail(row) {
        this.openDialogTableForm(2, row)
      },
      apply(row) {
        this.openDialogTableForm(2, row)
      },
      // 打开tableform窗口
      openDialogTableForm(editType, row) {
        this.editType = editType
        this.previewVisible = true
        let rowBck = {...row}
        if (editType == 1 || editType == 2) {
          this.detailId = row.id
          this.instanceId = rowBck.instanceId
          this.widgetModels = rowBck
        } else if (editType == 0) {
          for (const i in this.widgetModels) {
            this.widgetModels[i] = ''
          }
          this.widgetModels.btnList = ['1']
        }
      },
      // 查看字段明细
      handleViewField(row) {
        this.$router.push({
          path: 'system/formindex',
          query: {moduleName: row.moduleName, tableName: row.tableName, formDesc: row.formDesc, moduleFormId: row.id}
        })
      }

    }
  }
</script>
<style lang="scss">
  .el-dialog {
    border-radius: 15px;
  }
</style>
